<html lang="en-US">

<head>
    
<title>「番外」Golang 交叉编译 - 花落雨忧</title>

<meta property="og:title" content="「番外」Golang 交叉编译 - 花落雨忧">



    



    
    <meta property="description" content="在 连载九 讲解构建 Scratch 镜像时，我们编译可执行文件用了另外一个形式的命令，如下：
$ CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o go-gin-example . 我想你可能会有疑问，今天本文会针对这块进行讲解。
[&amp;hellip;] 我们将讲解命令各个参数的作用，希望你在阅读时，将每一项串联起来，你会发现这就 &amp;hellip;">
    <meta property="og:description" content="在 连载九 讲解构建 Scratch 镜像时，我们编译可执行文件用了另外一个形式的命令，如下：
$ CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o go-gin-example . 我想你可能会有疑问，今天本文会针对这块进行讲解。
[&amp;hellip;] 我们将讲解命令各个参数的作用，希望你在阅读时，将每一项串联起来，你会发现这就 &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/gin/2018-03-26-cgo/">「番外」Golang 交叉编译</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/03/26</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="知识点">知识点</h2>
<ul>
<li>跨平台编译</li>
</ul>
<h2 id="本文目标">本文目标</h2>
<p>在 <a href="https://segmentfault.com/a/1190000013960558">连载九</a> 讲解<strong>构建 Scratch 镜像</strong>时，我们编译可执行文件用了另外一个形式的命令，如下：</p>
<pre tabindex="0"><code>$ CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o go-gin-example .
</code></pre><p>我想你可能会有疑问，今天本文会针对这块进行讲解。</p>
<h2 id="说明">说明</h2>
<p>我们将讲解命令各个参数的作用，希望你在阅读时，将每一项串联起来，你会发现这就是<strong>交叉编译相关的小知识</strong></p>
<p>也就是 <code>Golang</code> 令人心动的特性之一<strong>跨平台编译</strong></p>
<h3 id="一cgo_enabled">一、CGO_ENABLED</h3>
<p><strong>作用：</strong></p>
<p>用于标识（声明） <code>cgo</code> 工具是否可用</p>
<p><strong>意义：</strong></p>
<p>存在交叉编译的情况时，<code>cgo</code> 工具是不可用的。在标准 go 命令的上下文环境中，交叉编译意味着程序构建环境的目标计算架构的标识与程序运行环境的目标计算架构的标识不同，或者程序构建环境的目标操作系统的标识与程序运行环境的目标操作系统的标识不同</p>
<p><strong>小结：</strong></p>
<p>结合案例来说，我们是在宿主机编译的可执行文件，而在 <code>Scratch</code> 镜像运行的可执行文件；显然两者的计算机架构、运行环境标识你无法确定它是否一致（毕竟构建的 <code>docker</code> 镜像还可以给他人使用），那么我们就要进行交叉编译，而交叉编译不支持 <code>cgo</code>，因此这里要禁用掉它</p>
<p>关闭 <code>cgo</code> 后，在构建过程中会忽略 <code>cgo</code> 并静态链接所有的依赖库，而开启 <code>cgo</code> 后，方式将转为动态链接</p>
<p><strong>补充：</strong></p>
<p><code>golang</code> 是默认开启 <code>cgo</code> 工具的，可执行 <code>go env</code> 命令查看</p>
<pre tabindex="0"><code>$ go env
GOARCH=&#34;amd64&#34;
GOBIN=&#34;&#34;
GOCACHE=&#34;/root/.cache/go-build&#34;
GOEXE=&#34;&#34;
GOHOSTARCH=&#34;amd64&#34;
GOHOSTOS=&#34;linux&#34;
GOOS=&#34;linux&#34;
...
GCCGO=&#34;gccgo&#34;
CC=&#34;gcc&#34;
CXX=&#34;g++&#34;
CGO_ENABLED=&#34;1&#34;
...
</code></pre><h3 id="二goos">二、GOOS</h3>
<p>用于标识（声明）程序构建环境的目标操作系统</p>
<p>如：</p>
<ul>
<li>linux</li>
<li>windows</li>
</ul>
<h3 id="三goarch">三、GOARCH</h3>
<p>用于标识（声明）程序构建环境的目标计算架构</p>
<p>若不设置，默认值与程序运行环境的目标计算架构一致（案例就是采用的默认值）</p>
<p>如：</p>
<ul>
<li>amd64</li>
<li>386</li>
</ul>
<table>
<thead>
<tr>
<th>系统</th>
<th>GOOS</th>
<th>GOARCH</th>
</tr>
</thead>
<tbody>
<tr>
<td>Windows 32 位</td>
<td>windows</td>
<td>386</td>
</tr>
<tr>
<td>Windows 64 位</td>
<td>windows</td>
<td>amd64</td>
</tr>
<tr>
<td>OS X 32 位</td>
<td>darwin</td>
<td>386</td>
</tr>
<tr>
<td>OS X 64 位</td>
<td>darwin</td>
<td>amd64</td>
</tr>
<tr>
<td>Linux 32 位</td>
<td>linux</td>
<td>386</td>
</tr>
<tr>
<td>Linux 64 位</td>
<td>linux</td>
<td>amd64</td>
</tr>
</tbody>
</table>
<h3 id="四gohostos">四、GOHOSTOS</h3>
<p>用于标识（声明）程序运行环境的目标操作系统</p>
<h3 id="五gohostarch">五、GOHOSTARCH</h3>
<p>用于标识（声明）程序运行环境的目标计算架构</p>
<h3 id="六go-build">六、go build</h3>
<h4 id="-a">-a</h4>
<p>强制重新编译，简单来说，就是不利用缓存或已编译好的部分文件，直接所有包都是最新的代码重新编译和关联</p>
<h4 id="-installsuffix">-installsuffix</h4>
<p><strong>作用：</strong></p>
<p>在软件包安装的目录中<strong>增加后缀标识</strong>，以保持输出与默认版本分开</p>
<p><strong>补充：</strong></p>
<p>如果使用 <code>-race</code> 标识，则后缀就会默认设置为 <code>-race</code> 标识，用于区别 <code>race</code> 和普通的版本</p>
<h4 id="-o">-o</h4>
<p>指定编译后的可执行文件名称</p>
<h3 id="小结">小结</h3>
<p>大部分参数指令，都有一定关联性，且与交叉编译的知识点相关，可以好好品味一下</p>
<p>最后可以看看 <code>go build help</code> 加深了解</p>
<pre tabindex="0"><code>$ go help build
usage: go build [-o output] [-i] [build flags] [packages]
...
	-a
		force rebuilding of packages that are already up-to-date.
	-n
		print the commands but do not run them.
	-p n
		the number of programs, such as build commands or
		test binaries, that can be run in parallel.
		The default is the number of CPUs available.
	-race
		enable data race detection.
		Supported only on linux/amd64, freebsd/amd64, darwin/amd64 and windows/amd64.
	-msan
		enable interoperation with memory sanitizer.
		Supported only on linux/amd64,
		and only with Clang/LLVM as the host C compiler.
	-v
		print the names of packages as they are compiled.
	-work
		print the name of the temporary work directory and
		do not delete it when exiting.
	-x
		print the commands.

	-asmflags &#39;[pattern=]arg list&#39;
		arguments to pass on each go tool asm invocation.
	-buildmode mode
		build mode to use. See &#39;go help buildmode&#39; for more.
	-compiler name
		name of compiler to use, as in runtime.Compiler (gccgo or gc).
	-gccgoflags &#39;[pattern=]arg list&#39;
		arguments to pass on each gccgo compiler/linker invocation.
	-gcflags &#39;[pattern=]arg list&#39;
		arguments to pass on each go tool compile invocation.
	-installsuffix suffix
		a suffix to use in the name of the package installation directory,
		in order to keep output separate from default builds.
		If using the -race flag, the install suffix is automatically set to race
		or, if set explicitly, has _race appended to it. Likewise for the -msan
		flag. Using a -buildmode option that requires non-default compile flags
		has a similar effect.
	-ldflags &#39;[pattern=]arg list&#39;
		arguments to pass on each go tool link invocation.
	-linkshared
		link against shared libraries previously created with
		-buildmode=shared.
	-pkgdir dir
		install and load all packages from dir instead of the usual locations.
		For example, when building with a non-standard configuration,
		use -pkgdir to keep generated packages in a separate location.
	-tags &#39;tag list&#39;
		a space-separated list of build tags to consider satisfied during the
		build. For more information about build tags, see the description of
		build constraints in the documentation for the go/build package.
	-toolexec &#39;cmd args&#39;
		a program to use to invoke toolchain programs like vet and asm.
		For example, instead of running asm, the go command will run
		&#39;cmd args /path/to/asm &lt;arguments for asm&gt;&#39;.
...
</code></pre><h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-gin-example">go-gin-example</a></li>
</ul>
<h3 id="书籍">书籍</h3>
<ul>
<li>Go 并发编程实战 第二版</li>
</ul>
<h2 id="关于">关于</h2>
<h3 id="修改记录">修改记录</h3>
<ul>
<li>第一版：2018 年 02 月 16 日发布文章</li>
<li>第二版：2019 年 10 月 01 日修改文章</li>
</ul>
<h2 id="heading">？</h2>
<p>如果有任何疑问或错误，欢迎在 <a href="https://github.com/EDDYCJY/blog">issues</a> 进行提问或给予修正意见，如果喜欢或对你有所帮助，欢迎 Star，对作者是一种鼓励和推进。</p>
<h3 id="我的公众号">我的公众号</h3>
<p><img src="https://image.eddycjy.com/8d0b0c3a11e74efd5fdfd7910257e70b.jpg" alt="image"></p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-03-24-golang-docker/">「连载九」将Golang应用部署到Docker</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-03-18-swagger/">「连载八」为它加上Swagger</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-03-15-reload-http/">「连载七」优雅的重启服务</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-02-15-log/">「连载六」编写一个简单的文件日志</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-02-14-jwt/">「连载五」使用 JWT 进行身份校验</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/gin" title="View all posts tagged match">gin</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/gin/2018-03-24-golang-docker/"
                                                    rel="prev">「连载九」将Golang应用部署到Docker</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/crawler/2018-04-01-cars/">爬取汽车之家 二手车产品库</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>